package pers.vic.basics.leetcode;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

/**
 * @description: 61. 旋转链表  {@literal https://leetcode-cn.com/problems/rotate-list/}
 * @author Vic.xu
 * @date: 2020/12/23 0023 8:26
 */
public class J0061_M_RotateRight {
    /*
    给定一个链表，旋转链表，将链表每个节点向右移动 k 个位置，其中 k 是非负数。
     */

    /**
     * 1. 先得到链表的长度，计算出偏移量，计算出新尾部节点的位置
     * 2. 把原链表尾首相连
     * 3. 遍历原来的链表，到新尾部的时候，把它的后面的节点作为头节点返回，并把此尾节点的next置为空
     */
    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }
        ListNode cur = head.next;
        ListNode tail = null;
        int size = 1;
        while (cur != null) {
            ListNode next = cur.next;
            //cur节点是tail节点的时候
            if (next == null) {
                tail = cur;
            }
            cur = next;
            size++;
        }
        //计算偏移量
        int offset = k % size;
        if (offset == 0) {
            return head;
        }
        //收尾相接起来
        tail.next = head;
        //新的尾部节点在哪个位置
        int newTailLocation = size - offset ;

        ListNode node = head;
        int num = 0;
        while (node != null) {
            num++;
            //遍历到需要标志的尾部节点的节点
            if (num == newTailLocation){
                ListNode curTail = node;
                ListNode newHead = node.next;
                curTail.next = null;
                return newHead;
            }
            node = node.next;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(new int[]{1,2});
        System.out.println(head);

        ListNode listNode = rotateRight(head, 2);
        //4->5->1->2->3->NULL
        System.out.println(listNode);
    }
}
